"use strict";
var __async = (__this, __arguments, generator) => {
  return new Promise((resolve, reject) => {
    var fulfilled = (value) => {
      try {
        step(generator.next(value));
      } catch (e) {
        reject(e);
      }
    };
    var rejected = (value) => {
      try {
        step(generator.throw(value));
      } catch (e) {
        reject(e);
      }
    };
    var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
    step((generator = generator.apply(__this, __arguments)).next());
  });
};
const taro = require("../../taro.js");
const common = require("../../common.js");
const index_vue_vue_type_style_index_0_lang = "";
const _sfc_main$2 = {
  name: "SudokuGrid",
  props: {
    // 初始数独题目
    puzzle: {
      type: Array,
      required: true
    },
    // 完整解答（用于提示）
    solution: {
      type: Array,
      default: () => []
    },
    // 是否只读模式
    readonly: {
      type: Boolean,
      default: false
    },
    // 是否显示数字输入面板
    showNumberPad: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      // 当前游戏网格
      grid: [],
      // 初始题目（用于判断哪些格子是只读的）
      initialPuzzle: [],
      // 选中的格子
      selectedCell: { row: -1, col: -1 },
      // 是否显示候选数字
      showCandidates: false,
      // 错误的格子
      errorCells: [],
      // 提示的格子
      hintCells: [],
      // 移动历史（用于撤销）
      moveHistory: [],
      // 游戏状态
      gameStatus: "playing"
      // playing, completed, error
    };
  },
  watch: {
    puzzle: {
      handler(newPuzzle) {
        this.initGame(newPuzzle);
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    /**
     * 初始化游戏
     */
    initGame(puzzle) {
      this.grid = JSON.parse(JSON.stringify(puzzle));
      this.initialPuzzle = JSON.parse(JSON.stringify(puzzle));
      this.selectedCell = { row: -1, col: -1 };
      this.errorCells = [];
      this.hintCells = [];
      this.moveHistory = [];
      this.gameStatus = "playing";
    },
    /**
     * 选择格子
     */
    selectCell(row, col) {
      console.log("选择格子:", { row, col, readonly: this.readonly });
      if (this.readonly) {
        console.log("游戏处于只读模式，无法选择格子");
        return;
      }
      this.selectedCell = { row, col };
      console.log("格子选择成功，当前选中:", this.selectedCell);
      this.clearErrors();
    },
    /**
     * 输入数字
     */
    inputNumber(num) {
      const { row, col } = this.selectedCell;
      if (row === -1 || col === -1) {
        this.$emit("message", "请先选择一个格子");
        return;
      }
      if (this.isReadonly(row, col)) {
        this.$emit("message", "该格子不能修改");
        return;
      }
      this.moveHistory.push({
        row,
        col,
        oldValue: this.grid[row][col],
        newValue: num,
        timestamp: Date.now()
      });
      this.grid[row][col] = num;
      this.validateMove(row, col, num);
      this.checkGameCompletion();
      this.$emit("move", {
        row,
        col,
        value: num,
        grid: JSON.parse(JSON.stringify(this.grid))
      });
    },
    /**
     * 清除数字
     */
    eraseNumber() {
      const { row, col } = this.selectedCell;
      if (row === -1 || col === -1)
        return;
      if (this.isReadonly(row, col)) {
        this.$emit("message", "该格子不能修改");
        return;
      }
      this.moveHistory.push({
        row,
        col,
        oldValue: this.grid[row][col],
        newValue: 0,
        timestamp: Date.now()
      });
      this.grid[row][col] = 0;
      this.clearErrors();
      this.$emit("move", {
        row,
        col,
        value: 0,
        grid: JSON.parse(JSON.stringify(this.grid))
      });
    },
    /**
     * 验证移动是否有效
     */
    validateMove(row, col, num) {
      const originalValue = this.grid[row][col];
      this.grid[row][col] = 0;
      if (!common.isValidMove(this.grid, row, col, num)) {
        this.errorCells.push({ row, col });
        this.$emit("error", "数字冲突！");
      } else {
        this.clearErrors();
      }
      this.grid[row][col] = originalValue;
    },
    /**
     * 检查游戏是否完成
     */
    checkGameCompletion() {
      if (common.isValidSudoku(this.grid)) {
        this.gameStatus = "completed";
        this.$emit("complete", {
          grid: JSON.parse(JSON.stringify(this.grid)),
          moves: this.moveHistory.length,
          time: Date.now()
        });
      }
    },
    /**
     * 获取提示
     */
    getHint() {
      console.log("=== 提示功能调试开始 ===");
      console.log("提示按钮被点击");
      const { row, col } = this.selectedCell;
      console.log("选中的格子:", { row, col });
      if (row === -1 || col === -1) {
        console.log("错误: 没有选中格子");
        this.$emit("message", "请先选择一个格子");
        return;
      }
      console.log("当前格子的值:", this.grid[row][col]);
      if (this.grid[row][col] !== 0) {
        console.log("错误: 格子已有数字");
        this.$emit("message", "该格子已有数字");
        return;
      }
      console.log("解答数据长度:", this.solution.length);
      console.log("解答数据:", this.solution);
      if (this.solution.length === 0) {
        console.log("错误: 没有解答数据");
        this.$emit("message", "暂无提示可用");
        return;
      }
      const hint = common.getHint(this.grid, this.solution, row, col);
      console.log("获取到的提示:", hint);
      if (hint !== null && hint !== void 0 && hint >= 1 && hint <= 9) {
        console.log("提示成功，填入数字:", hint);
        this.hintCells.push({ row, col });
        this.inputNumber(hint);
        this.$emit("hint-used", { row, col, value: hint });
      } else {
        console.log("错误: 提示数字无效或无法获取提示，hint值:", hint);
        this.$emit("message", "该位置暂无有效提示");
      }
      console.log("=== 提示功能调试结束 ===");
    },
    /**
     * 撤销移动
     */
    undoMove() {
      if (this.moveHistory.length === 0) {
        this.$emit("message", "没有可撤销的移动");
        return;
      }
      const lastMove = this.moveHistory.pop();
      this.grid[lastMove.row][lastMove.col] = lastMove.oldValue;
      this.clearErrors();
      this.$emit("undo", lastMove);
    },
    /**
     * 重置游戏
     */
    resetGame() {
      this.initGame(this.initialPuzzle);
      this.$emit("reset");
    },
    /**
     * 切换候选数字显示
     */
    toggleCandidates() {
      this.showCandidates = !this.showCandidates;
    },
    /**
     * 获取候选数字
     */
    getCandidates(row, col) {
      if (this.grid[row][col] !== 0)
        return [];
      return common.getPossibleNumbers(this.grid, row, col);
    },
    /**
     * 检查是否可以放置数字
     */
    canPlaceNumber(num) {
      const { row, col } = this.selectedCell;
      if (row === -1 || col === -1)
        return false;
      if (this.isReadonly(row, col))
        return false;
      return common.isValidMove(this.grid, row, col, num);
    },
    /**
     * 检查格子是否有错误
     */
    hasError(row, col) {
      return this.errorCells.some((cell) => cell.row === row && cell.col === col);
    },
    /**
     * 检查是否是提示格子
     */
    isHintCell(row, col) {
      return this.hintCells.some((cell) => cell.row === row && cell.col === col);
    },
    /**
     * 检查格子是否只读
     */
    isReadonly(row, col) {
      return this.initialPuzzle[row][col] !== 0;
    },
    /**
     * 检查是否应该高亮
     */
    shouldHighlight(row, col) {
      const { row: selectedRow, col: selectedCol } = this.selectedCell;
      if (selectedRow === -1 || selectedCol === -1)
        return false;
      return row === selectedRow || col === selectedCol || Math.floor(row / 3) === Math.floor(selectedRow / 3) && Math.floor(col / 3) === Math.floor(selectedCol / 3);
    },
    /**
     * 清除错误标记
     */
    clearErrors() {
      this.errorCells = [];
    },
    /**
     * 获取当前网格状态
     */
    getGridState() {
      return {
        grid: JSON.parse(JSON.stringify(this.grid)),
        moveHistory: [...this.moveHistory],
        gameStatus: this.gameStatus
      };
    }
  }
};
const _hoisted_1$2 = { class: "sudoku-grid" };
const _hoisted_2$2 = { class: "grid-container" };
const _hoisted_3$2 = ["onTap"];
const _hoisted_4$2 = {
  key: 0,
  class: "cell-number"
};
const _hoisted_5$2 = {
  key: 1,
  class: "candidates"
};
const _hoisted_6$1 = {
  key: 0,
  class: "number-pad"
};
const _hoisted_7$1 = { class: "number-row" };
const _hoisted_8$1 = ["onTap"];
const _hoisted_9$1 = { class: "btn-text" };
const _hoisted_10$1 = { class: "number-row" };
const _hoisted_11$1 = ["onTap"];
const _hoisted_12$1 = { class: "btn-text" };
const _hoisted_13$1 = { class: "game-controls" };
const _hoisted_14$1 = { class: "btn-text" };
function _sfc_render$2(_ctx, _cache, $props, $setup, $data, $options) {
  return taro.openBlock(), taro.createElementBlock("view", _hoisted_1$2, [
    taro.createCommentVNode(" 数独网格 "),
    taro.createBaseVNode("view", _hoisted_2$2, [
      (taro.openBlock(true), taro.createElementBlock(
        taro.Fragment,
        null,
        taro.renderList($data.grid, (row, rowIndex) => {
          return taro.openBlock(), taro.createElementBlock("view", {
            key: rowIndex,
            class: "grid-row"
          }, [
            (taro.openBlock(true), taro.createElementBlock(
              taro.Fragment,
              null,
              taro.renderList(row, (cell, colIndex) => {
                return taro.openBlock(), taro.createElementBlock("view", {
                  key: colIndex,
                  class: taro.normalizeClass(["grid-cell", {
                    "cell-filled": cell !== 0,
                    "cell-selected": $data.selectedCell.row === rowIndex && $data.selectedCell.col === colIndex,
                    "cell-error": $options.hasError(rowIndex, colIndex),
                    "cell-hint": $options.isHintCell(rowIndex, colIndex),
                    "cell-readonly": $options.isReadonly(rowIndex, colIndex),
                    "cell-highlight": $options.shouldHighlight(rowIndex, colIndex),
                    "border-right": (colIndex + 1) % 3 === 0 && colIndex !== 8,
                    "border-bottom": (rowIndex + 1) % 3 === 0 && rowIndex !== 8
                  }]),
                  onTap: ($event) => $options.selectCell(rowIndex, colIndex)
                }, [
                  cell !== 0 ? (taro.openBlock(), taro.createElementBlock(
                    "text",
                    _hoisted_4$2,
                    taro.toDisplayString(cell),
                    1
                    /* TEXT */
                  )) : taro.createCommentVNode("v-if", true),
                  taro.createCommentVNode(" 候选数字 "),
                  cell === 0 && $data.showCandidates ? (taro.openBlock(), taro.createElementBlock("view", _hoisted_5$2, [
                    (taro.openBlock(true), taro.createElementBlock(
                      taro.Fragment,
                      null,
                      taro.renderList($options.getCandidates(rowIndex, colIndex), (num) => {
                        return taro.openBlock(), taro.createElementBlock(
                          "text",
                          {
                            key: num,
                            class: "candidate-number"
                          },
                          taro.toDisplayString(num),
                          1
                          /* TEXT */
                        );
                      }),
                      128
                      /* KEYED_FRAGMENT */
                    ))
                  ])) : taro.createCommentVNode("v-if", true)
                ], 42, _hoisted_3$2);
              }),
              128
              /* KEYED_FRAGMENT */
            ))
          ]);
        }),
        128
        /* KEYED_FRAGMENT */
      ))
    ]),
    taro.createCommentVNode(" 数字输入面板 "),
    $props.showNumberPad ? (taro.openBlock(), taro.createElementBlock("view", _hoisted_6$1, [
      taro.createBaseVNode("view", _hoisted_7$1, [
        (taro.openBlock(), taro.createElementBlock(
          taro.Fragment,
          null,
          taro.renderList([1, 2, 3, 4, 5], (num) => {
            return taro.createBaseVNode("view", {
              key: num,
              class: taro.normalizeClass(["number-btn", { "btn-disabled": !$options.canPlaceNumber(num) }]),
              onTap: ($event) => $options.inputNumber(num)
            }, [
              taro.createBaseVNode(
                "text",
                _hoisted_9$1,
                taro.toDisplayString(num),
                1
                /* TEXT */
              )
            ], 42, _hoisted_8$1);
          }),
          64
          /* STABLE_FRAGMENT */
        ))
      ]),
      taro.createBaseVNode("view", _hoisted_10$1, [
        (taro.openBlock(), taro.createElementBlock(
          taro.Fragment,
          null,
          taro.renderList([6, 7, 8, 9], (num) => {
            return taro.createBaseVNode("view", {
              key: num,
              class: taro.normalizeClass(["number-btn", { "btn-disabled": !$options.canPlaceNumber(num) }]),
              onTap: ($event) => $options.inputNumber(num)
            }, [
              taro.createBaseVNode(
                "text",
                _hoisted_12$1,
                taro.toDisplayString(num),
                1
                /* TEXT */
              )
            ], 42, _hoisted_11$1);
          }),
          64
          /* STABLE_FRAGMENT */
        )),
        taro.createBaseVNode(
          "view",
          {
            class: "number-btn erase-btn",
            onTap: _cache[0] || (_cache[0] = (...args) => $options.eraseNumber && $options.eraseNumber(...args))
          },
          _cache[5] || (_cache[5] = [
            taro.createBaseVNode(
              "text",
              { class: "btn-text" },
              "清除",
              -1
              /* CACHED */
            )
          ]),
          32
          /* NEED_HYDRATION */
        )
      ])
    ])) : taro.createCommentVNode("v-if", true),
    taro.createCommentVNode(" 游戏控制按钮 "),
    taro.createBaseVNode("view", _hoisted_13$1, [
      taro.createBaseVNode(
        "view",
        {
          class: "control-btn",
          onTap: _cache[1] || (_cache[1] = (...args) => $options.toggleCandidates && $options.toggleCandidates(...args))
        },
        [
          taro.createBaseVNode(
            "text",
            _hoisted_14$1,
            taro.toDisplayString($data.showCandidates ? "隐藏" : "显示") + "候选",
            1
            /* TEXT */
          )
        ],
        32
        /* NEED_HYDRATION */
      ),
      taro.createBaseVNode(
        "view",
        {
          class: "control-btn",
          onTap: _cache[2] || (_cache[2] = (...args) => $options.getHint && $options.getHint(...args))
        },
        _cache[6] || (_cache[6] = [
          taro.createBaseVNode(
            "text",
            { class: "btn-text" },
            "提示",
            -1
            /* CACHED */
          )
        ]),
        32
        /* NEED_HYDRATION */
      ),
      taro.createBaseVNode(
        "view",
        {
          class: "control-btn",
          onTap: _cache[3] || (_cache[3] = (...args) => $options.undoMove && $options.undoMove(...args))
        },
        _cache[7] || (_cache[7] = [
          taro.createBaseVNode(
            "text",
            { class: "btn-text" },
            "撤销",
            -1
            /* CACHED */
          )
        ]),
        32
        /* NEED_HYDRATION */
      ),
      taro.createBaseVNode(
        "view",
        {
          class: "control-btn",
          onTap: _cache[4] || (_cache[4] = (...args) => $options.resetGame && $options.resetGame(...args))
        },
        _cache[8] || (_cache[8] = [
          taro.createBaseVNode(
            "text",
            { class: "btn-text" },
            "重置",
            -1
            /* CACHED */
          )
        ]),
        32
        /* NEED_HYDRATION */
      )
    ])
  ]);
}
const SudokuGrid = /* @__PURE__ */ common._export_sfc(_sfc_main$2, [["render", _sfc_render$2], ["__file", "D:/code/数独/sudoku-game/src/components/SudokuGrid/index.vue"]]);
const index_vue_vue_type_style_index_0_scoped_62f45914_lang = "";
const _sfc_main$1 = {
  name: "Timer",
  props: {
    // 是否自动开始
    autoStart: {
      type: Boolean,
      default: true
    },
    // 是否显示控制按钮
    showControls: {
      type: Boolean,
      default: false
    },
    // 初始时间（秒）
    initialTime: {
      type: Number,
      default: 0
    },
    // 是否为倒计时模式
    countdown: {
      type: Boolean,
      default: false
    },
    // 倒计时总时间（秒）
    countdownTime: {
      type: Number,
      default: 300
      // 5分钟
    }
  },
  data() {
    return {
      // 当前时间（秒）
      currentTime: 0,
      // 计时器是否运行
      isRunning: false,
      // 计时器实例
      timer: null,
      // 开始时间戳
      startTime: null,
      // 暂停时的累计时间
      pausedTime: 0
    };
  },
  computed: {
    /**
     * 格式化时间显示
     */
    formattedTime() {
      const time = this.countdown ? this.countdownTime - this.currentTime : this.currentTime;
      const minutes = Math.floor(Math.abs(time) / 60);
      const seconds = Math.abs(time) % 60;
      const sign = time < 0 ? "-" : "";
      return `${sign}${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`;
    }
  },
  watch: {
    currentTime(newTime) {
      if (this.countdown && newTime >= this.countdownTime) {
        this.stopTimer();
        this.$emit("timeout");
      }
      this.$emit("time-update", {
        currentTime: newTime,
        formattedTime: this.formattedTime,
        isRunning: this.isRunning
      });
    }
  },
  mounted() {
    this.currentTime = this.initialTime;
    if (this.autoStart) {
      this.startTimer();
    }
  },
  beforeDestroy() {
    this.clearTimer();
  },
  methods: {
    /**
     * 开始计时
     */
    startTimer() {
      if (this.isRunning)
        return;
      this.isRunning = true;
      this.startTime = Date.now() - this.pausedTime * 1e3;
      this.timer = setInterval(() => {
        const elapsed = Math.floor((Date.now() - this.startTime) / 1e3);
        this.currentTime = this.initialTime + elapsed;
      }, 1e3);
      this.$emit("start", {
        currentTime: this.currentTime,
        timestamp: Date.now()
      });
    },
    /**
     * 暂停计时
     */
    pauseTimer() {
      if (!this.isRunning)
        return;
      this.isRunning = false;
      this.pausedTime = this.currentTime - this.initialTime;
      this.clearTimer();
      this.$emit("pause", {
        currentTime: this.currentTime,
        timestamp: Date.now()
      });
    },
    /**
     * 停止计时
     */
    stopTimer() {
      this.isRunning = false;
      this.clearTimer();
      this.$emit("stop", {
        currentTime: this.currentTime,
        totalTime: this.currentTime - this.initialTime,
        timestamp: Date.now()
      });
    },
    /**
     * 重置计时器
     */
    resetTimer() {
      this.isRunning = false;
      this.currentTime = this.initialTime;
      this.pausedTime = 0;
      this.startTime = null;
      this.clearTimer();
      this.$emit("reset", {
        timestamp: Date.now()
      });
    },
    /**
     * 切换计时器状态
     */
    toggleTimer() {
      if (this.isRunning) {
        this.pauseTimer();
      } else {
        this.startTimer();
      }
    },
    /**
     * 清除计时器
     */
    clearTimer() {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    },
    /**
     * 设置时间
     */
    setTime(seconds) {
      this.currentTime = seconds;
      this.pausedTime = seconds - this.initialTime;
    },
    /**
     * 获取当前状态
     */
    getState() {
      return {
        currentTime: this.currentTime,
        isRunning: this.isRunning,
        formattedTime: this.formattedTime,
        totalTime: this.currentTime - this.initialTime
      };
    }
  }
};
const _hoisted_1$1 = { class: "timer-container" };
const _hoisted_2$1 = { class: "timer-display" };
const _hoisted_3$1 = { class: "time-text" };
const _hoisted_4$1 = {
  key: 0,
  class: "timer-controls"
};
const _hoisted_5$1 = { class: "btn-text" };
function _sfc_render$1(_ctx, _cache, $props, $setup, $data, $options) {
  return taro.openBlock(), taro.createElementBlock("view", _hoisted_1$1, [
    taro.createBaseVNode("view", _hoisted_2$1, [
      taro.createBaseVNode(
        "text",
        _hoisted_3$1,
        taro.toDisplayString($options.formattedTime),
        1
        /* TEXT */
      )
    ]),
    $props.showControls ? (taro.openBlock(), taro.createElementBlock("view", _hoisted_4$1, [
      taro.createBaseVNode(
        "view",
        {
          class: "control-btn",
          onTap: _cache[0] || (_cache[0] = (...args) => $options.toggleTimer && $options.toggleTimer(...args))
        },
        [
          taro.createBaseVNode(
            "text",
            _hoisted_5$1,
            taro.toDisplayString($data.isRunning ? "暂停" : "开始"),
            1
            /* TEXT */
          )
        ],
        32
        /* NEED_HYDRATION */
      ),
      taro.createBaseVNode(
        "view",
        {
          class: "control-btn reset-btn",
          onTap: _cache[1] || (_cache[1] = (...args) => $options.resetTimer && $options.resetTimer(...args))
        },
        _cache[2] || (_cache[2] = [
          taro.createBaseVNode(
            "text",
            { class: "btn-text" },
            "重置",
            -1
            /* CACHED */
          )
        ]),
        32
        /* NEED_HYDRATION */
      )
    ])) : taro.createCommentVNode("v-if", true)
  ]);
}
const Timer = /* @__PURE__ */ common._export_sfc(_sfc_main$1, [["render", _sfc_render$1], ["__scopeId", "data-v-62f45914"], ["__file", "D:/code/数独/sudoku-game/src/components/Timer/index.vue"]]);
const index = "";
const _sfc_main = {
  name: "GamePage",
  components: {
    SudokuGrid,
    Timer
  },
  setup() {
    const currentPuzzle = taro.ref([]);
    const currentSolution = taro.ref([]);
    const currentDifficulty = taro.ref(common.DIFFICULTY.MEDIUM);
    const gameStatus = taro.ref("loading");
    const score = taro.ref(0);
    const hintsUsed = taro.ref(0);
    const maxHints = taro.ref(3);
    const errors = taro.ref(0);
    const maxErrors = taro.ref(3);
    const gameTime = taro.ref(0);
    const showCompletionModal = taro.ref(false);
    const completionTime = taro.ref("");
    const finalScore = taro.ref(0);
    const timer = taro.ref(null);
    const sudokuGrid = taro.ref(null);
    const difficultyText = taro.computed(() => {
      const textMap = {
        [common.DIFFICULTY.EASY]: "简单",
        [common.DIFFICULTY.MEDIUM]: "中等",
        [common.DIFFICULTY.HARD]: "困难",
        [common.DIFFICULTY.EXPERT]: "专家"
      };
      return textMap[currentDifficulty.value] || "中等";
    });
    const remainingCells = taro.computed(() => {
      if (!currentPuzzle.value.length)
        return 0;
      let count = 0;
      for (let i = 0; i < 9; i++) {
        for (let j = 0; j < 9; j++) {
          if (currentPuzzle.value[i][j] === 0)
            count++;
        }
      }
      return count;
    });
    const initGame = () => __async(this, null, function* () {
      var _a, _b;
      try {
        gameStatus.value = "loading";
        try {
          console.log("=== 开始获取服务器题目 ===");
          console.log("请求难度:", currentDifficulty.value);
          const puzzleData = yield common.gameAPI.getSudokuPuzzle(currentDifficulty.value);
          console.log("服务器返回数据:", puzzleData);
          console.log("题目数据长度:", (_a = puzzleData.puzzle) == null ? void 0 : _a.length);
          console.log("解答数据长度:", (_b = puzzleData.solution) == null ? void 0 : _b.length);
          currentPuzzle.value = puzzleData.puzzle;
          currentSolution.value = puzzleData.solution;
          console.log("服务器题目获取成功");
          console.log("当前题目:", currentPuzzle.value);
          console.log("当前解答:", currentSolution.value);
        } catch (error) {
          console.log("=== 服务器获取失败，使用本地生成 ===");
          console.log("错误信息:", error);
          const puzzleData = common.generateSudokuPuzzle(currentDifficulty.value);
          console.log("本地生成数据:", puzzleData);
          currentPuzzle.value = puzzleData.puzzle;
          currentSolution.value = puzzleData.solution;
          console.log("本地题目生成成功");
        }
        score.value = 0;
        hintsUsed.value = 0;
        errors.value = 0;
        gameTime.value = 0;
        showCompletionModal.value = false;
        gameStatus.value = "playing";
        if (timer.value) {
          timer.value.resetTimer();
          timer.value.startTimer();
        }
      } catch (error) {
        console.error("初始化游戏失败:", error);
        showMessage("游戏初始化失败");
      }
    });
    const newGame = () => {
      if (typeof taro.Taro.showModal === "function") {
        taro.Taro.showModal({
          title: "新游戏",
          content: "确定要开始新游戏吗？当前进度将丢失。",
          success: (res) => {
            if (res.confirm) {
              initGame();
            }
          }
        });
      } else {
        if (confirm("确定要开始新游戏吗？当前进度将丢失。")) {
          initGame();
        }
      }
    };
    const pauseGame = () => {
      if (gameStatus.value === "playing") {
        gameStatus.value = "paused";
        if (timer.value) {
          timer.value.pauseTimer();
        }
      } else if (gameStatus.value === "paused") {
        resumeGame();
      }
    };
    const resumeGame = () => {
      gameStatus.value = "playing";
      if (timer.value) {
        timer.value.startTimer();
      }
    };
    const showMenu = () => {
      if (typeof taro.Taro.showActionSheet === "function") {
        taro.Taro.showActionSheet({
          itemList: ["选择难度", "查看排行榜", "游戏设置", "关于游戏"],
          success: (res) => {
            switch (res.tapIndex) {
              case 0:
                selectDifficulty();
                break;
              case 1:
                taro.Taro.navigateTo({ url: "/pages/leaderboard/index" });
                break;
              case 2:
                taro.Taro.navigateTo({ url: "/pages/settings/index" });
                break;
              case 3:
                taro.Taro.navigateTo({ url: "/pages/about/index" });
                break;
            }
          }
        });
      } else {
        const choice = prompt("请选择操作：\n0 - 选择难度\n1 - 查看排行榜\n2 - 游戏设置\n3 - 关于游戏");
        const index2 = parseInt(choice);
        if (index2 >= 0 && index2 <= 3) {
          switch (index2) {
            case 0:
              selectDifficulty();
              break;
            case 1:
              taro.taroWindowProvider.location.hash = "#/pages/leaderboard/index";
              break;
            case 2:
              showMessage("游戏设置功能开发中");
              break;
            case 3:
              showMessage("关于游戏功能开发中");
              break;
          }
        }
      }
    };
    const selectDifficulty = () => {
      if (typeof taro.Taro.showActionSheet === "function") {
        taro.Taro.showActionSheet({
          itemList: ["简单", "中等", "困难", "专家"],
          success: (res) => {
            const difficulties = [common.DIFFICULTY.EASY, common.DIFFICULTY.MEDIUM, common.DIFFICULTY.HARD, common.DIFFICULTY.EXPERT];
            currentDifficulty.value = difficulties[res.tapIndex];
            initGame();
          }
        });
      } else {
        const choice = prompt("请选择难度：\n0 - 简单\n1 - 中等\n2 - 困难\n3 - 专家");
        const index2 = parseInt(choice);
        if (index2 >= 0 && index2 <= 3) {
          const difficulties = [common.DIFFICULTY.EASY, common.DIFFICULTY.MEDIUM, common.DIFFICULTY.HARD, common.DIFFICULTY.EXPERT];
          currentDifficulty.value = difficulties[index2];
          initGame();
        }
      }
    };
    const onPlayerMove = (moveData) => {
      if (moveData.value !== 0) {
        score.value += 10;
      }
    };
    const onGameComplete = (completionData) => __async(this, null, function* () {
      gameStatus.value = "completed";
      if (timer.value) {
        timer.value.stopTimer();
        const timerState = timer.value.getState();
        gameTime.value = timerState.totalTime;
        completionTime.value = timerState.formattedTime;
      }
      const timeBonus = Math.max(0, 1e3 - gameTime.value);
      const hintPenalty = hintsUsed.value * 50;
      const errorPenalty = errors.value * 100;
      finalScore.value = score.value + timeBonus - hintPenalty - errorPenalty;
      showCompletionModal.value = true;
      try {
        yield common.gameAPI.submitGameResult({
          difficulty: currentDifficulty.value,
          time: gameTime.value,
          score: finalScore.value,
          hintsUsed: hintsUsed.value,
          errors: errors.value,
          completed: true
        });
      } catch (error) {
        console.log("提交游戏结果失败:", error);
      }
    });
    const onGameError = (errorMessage) => {
      errors.value++;
      showMessage(errorMessage);
      if (errors.value >= maxErrors) {
        gameStatus.value = "failed";
        showMessage("游戏失败！错误次数过多");
      }
    };
    const onHintUsed = (hintData) => {
      hintsUsed.value++;
      score.value = Math.max(0, score.value - 20);
    };
    const onTimeUpdate = (timeData) => {
      gameTime.value = timeData.currentTime;
    };
    const onTimeout = () => {
      gameStatus.value = "timeout";
      showMessage("时间到！游戏结束");
    };
    const hideCompletionModal = () => {
      showCompletionModal.value = false;
    };
    const shareResult = () => {
      if (typeof taro.Taro.showShareMenu === "function") {
        taro.Taro.showShareMenu({
          withShareTicket: true
        });
      } else {
        if (taro.nav.share) {
          taro.nav.share({
            title: "数独游戏",
            text: `我在数独游戏中获得了${finalScore.value}分！用时${completionTime.value}`,
            url: taro.taroWindowProvider.location.href
          });
        } else {
          const shareText = `我在数独游戏中获得了${finalScore.value}分！用时${completionTime.value} - ${taro.taroWindowProvider.location.href}`;
          if (taro.nav.clipboard) {
            taro.nav.clipboard.writeText(shareText).then(() => {
              showMessage("分享链接已复制到剪贴板");
            });
          } else {
            showMessage("分享功能在此环境下不可用");
          }
        }
      }
    };
    const playAgain = () => {
      hideCompletionModal();
      initGame();
    };
    const showMessage = (message) => {
      if (typeof taro.Taro.showToast === "function") {
        taro.Taro.showToast({
          title: message,
          icon: "none",
          duration: 2e3
        });
      } else {
        {
          console.log(message);
        }
      }
    };
    taro.onMounted(() => {
      initGame();
    });
    return {
      // 数据
      currentPuzzle,
      currentSolution,
      currentDifficulty,
      gameStatus,
      score,
      hintsUsed,
      maxHints,
      errors,
      maxErrors,
      gameTime,
      showCompletionModal,
      completionTime,
      finalScore,
      // 计算属性
      difficultyText,
      remainingCells,
      // 组件引用
      timer,
      sudokuGrid,
      // 方法
      initGame,
      newGame,
      pauseGame,
      resumeGame,
      showMenu,
      selectDifficulty,
      onPlayerMove,
      onGameComplete,
      onGameError,
      onHintUsed,
      onTimeUpdate,
      onTimeout,
      hideCompletionModal,
      shareResult,
      playAgain,
      showMessage
    };
  }
};
const _hoisted_1 = { class: "game-page" };
const _hoisted_2 = { class: "game-header" };
const _hoisted_3 = { class: "header-left" };
const _hoisted_4 = { class: "badge-text" };
const _hoisted_5 = { class: "header-center" };
const _hoisted_6 = { class: "header-right" };
const _hoisted_7 = { class: "score-display" };
const _hoisted_8 = { class: "score-text" };
const _hoisted_9 = { class: "game-status" };
const _hoisted_10 = { class: "status-item" };
const _hoisted_11 = { class: "status-value" };
const _hoisted_12 = { class: "status-item" };
const _hoisted_13 = { class: "status-value" };
const _hoisted_14 = { class: "status-item" };
const _hoisted_15 = { class: "status-value" };
const _hoisted_16 = { class: "game-controls" };
const _hoisted_17 = { class: "control-row" };
const _hoisted_18 = { class: "btn-text" };
const _hoisted_19 = { class: "modal-content" };
const _hoisted_20 = { class: "result-item" };
const _hoisted_21 = { class: "result-value" };
const _hoisted_22 = { class: "result-item" };
const _hoisted_23 = { class: "result-value" };
const _hoisted_24 = { class: "result-item" };
const _hoisted_25 = { class: "result-value" };
const _hoisted_26 = { class: "modal-actions" };
const _hoisted_27 = {
  key: 1,
  class: "pause-overlay"
};
const _hoisted_28 = { class: "pause-content" };
function _sfc_render(_ctx, _cache, $props, $setup, $data, $options) {
  const _component_Timer = taro.resolveComponent("Timer");
  const _component_SudokuGrid = taro.resolveComponent("SudokuGrid");
  return taro.openBlock(), taro.createElementBlock("view", _hoisted_1, [
    taro.createCommentVNode(" 游戏头部 "),
    taro.createBaseVNode("view", _hoisted_2, [
      taro.createBaseVNode("view", _hoisted_3, [
        taro.createBaseVNode(
          "view",
          {
            class: taro.normalizeClass(["difficulty-badge", `difficulty-${$setup.currentDifficulty}`])
          },
          [
            taro.createBaseVNode(
              "text",
              _hoisted_4,
              taro.toDisplayString($setup.difficultyText),
              1
              /* TEXT */
            )
          ],
          2
          /* CLASS */
        )
      ]),
      taro.createBaseVNode("view", _hoisted_5, [
        taro.createVNode(_component_Timer, {
          ref: "timer",
          "auto-start": false,
          onTimeUpdate: $setup.onTimeUpdate,
          onTimeout: $setup.onTimeout
        }, null, 8, ["onTimeUpdate", "onTimeout"])
      ]),
      taro.createBaseVNode("view", _hoisted_6, [
        taro.createBaseVNode("view", _hoisted_7, [
          taro.createBaseVNode(
            "text",
            _hoisted_8,
            "分数: " + taro.toDisplayString($setup.score),
            1
            /* TEXT */
          )
        ])
      ])
    ]),
    taro.createCommentVNode(" 游戏状态栏 "),
    taro.createBaseVNode("view", _hoisted_9, [
      taro.createBaseVNode("view", _hoisted_10, [
        _cache[8] || (_cache[8] = taro.createBaseVNode(
          "text",
          { class: "status-label" },
          "剩余:",
          -1
          /* CACHED */
        )),
        taro.createBaseVNode(
          "text",
          _hoisted_11,
          taro.toDisplayString($setup.remainingCells),
          1
          /* TEXT */
        )
      ]),
      taro.createBaseVNode("view", _hoisted_12, [
        _cache[9] || (_cache[9] = taro.createBaseVNode(
          "text",
          { class: "status-label" },
          "提示:",
          -1
          /* CACHED */
        )),
        taro.createBaseVNode(
          "text",
          _hoisted_13,
          taro.toDisplayString($setup.hintsUsed) + "/" + taro.toDisplayString($setup.maxHints),
          1
          /* TEXT */
        )
      ]),
      taro.createBaseVNode("view", _hoisted_14, [
        _cache[10] || (_cache[10] = taro.createBaseVNode(
          "text",
          { class: "status-label" },
          "错误:",
          -1
          /* CACHED */
        )),
        taro.createBaseVNode(
          "text",
          _hoisted_15,
          taro.toDisplayString($setup.errors) + "/" + taro.toDisplayString($setup.maxErrors),
          1
          /* TEXT */
        )
      ])
    ]),
    taro.createCommentVNode(" 数独网格 "),
    taro.createVNode(_component_SudokuGrid, {
      ref: "sudokuGrid",
      puzzle: $setup.currentPuzzle,
      solution: $setup.currentSolution,
      readonly: $setup.gameStatus !== "playing",
      onMove: $setup.onPlayerMove,
      onComplete: $setup.onGameComplete,
      onError: $setup.onGameError,
      onHintUsed: $setup.onHintUsed,
      onMessage: $setup.showMessage
    }, null, 8, ["puzzle", "solution", "readonly", "onMove", "onComplete", "onError", "onHintUsed", "onMessage"]),
    taro.createCommentVNode(" 游戏控制面板 "),
    taro.createBaseVNode("view", _hoisted_16, [
      taro.createBaseVNode("view", _hoisted_17, [
        taro.createBaseVNode(
          "view",
          {
            class: "control-btn",
            onTap: _cache[0] || (_cache[0] = (...args) => $setup.newGame && $setup.newGame(...args))
          },
          _cache[11] || (_cache[11] = [
            taro.createBaseVNode(
              "text",
              { class: "btn-text" },
              "新游戏",
              -1
              /* CACHED */
            )
          ]),
          32
          /* NEED_HYDRATION */
        ),
        taro.createBaseVNode(
          "view",
          {
            class: "control-btn",
            onTap: _cache[1] || (_cache[1] = (...args) => $setup.pauseGame && $setup.pauseGame(...args))
          },
          [
            taro.createBaseVNode(
              "text",
              _hoisted_18,
              taro.toDisplayString($setup.gameStatus === "paused" ? "继续" : "暂停"),
              1
              /* TEXT */
            )
          ],
          32
          /* NEED_HYDRATION */
        ),
        taro.createBaseVNode(
          "view",
          {
            class: "control-btn",
            onTap: _cache[2] || (_cache[2] = (...args) => $setup.showMenu && $setup.showMenu(...args))
          },
          _cache[12] || (_cache[12] = [
            taro.createBaseVNode(
              "text",
              { class: "btn-text" },
              "菜单",
              -1
              /* CACHED */
            )
          ]),
          32
          /* NEED_HYDRATION */
        )
      ])
    ]),
    taro.createCommentVNode(" 游戏完成弹窗 "),
    $setup.showCompletionModal ? (taro.openBlock(), taro.createElementBlock(
      "view",
      {
        key: 0,
        class: "modal-overlay",
        onTap: _cache[6] || (_cache[6] = (...args) => $setup.hideCompletionModal && $setup.hideCompletionModal(...args))
      },
      [
        taro.createBaseVNode(
          "view",
          {
            class: "completion-modal",
            onTap: _cache[5] || (_cache[5] = taro.withModifiers(() => {
            }, ["stop"]))
          },
          [
            _cache[18] || (_cache[18] = taro.createBaseVNode(
              "view",
              { class: "modal-header" },
              [
                taro.createBaseVNode("text", { class: "modal-title" }, "🎉 恭喜完成！")
              ],
              -1
              /* CACHED */
            )),
            taro.createBaseVNode("view", _hoisted_19, [
              taro.createBaseVNode("view", _hoisted_20, [
                _cache[13] || (_cache[13] = taro.createBaseVNode(
                  "text",
                  { class: "result-label" },
                  "用时:",
                  -1
                  /* CACHED */
                )),
                taro.createBaseVNode(
                  "text",
                  _hoisted_21,
                  taro.toDisplayString($setup.completionTime),
                  1
                  /* TEXT */
                )
              ]),
              taro.createBaseVNode("view", _hoisted_22, [
                _cache[14] || (_cache[14] = taro.createBaseVNode(
                  "text",
                  { class: "result-label" },
                  "分数:",
                  -1
                  /* CACHED */
                )),
                taro.createBaseVNode(
                  "text",
                  _hoisted_23,
                  taro.toDisplayString($setup.finalScore),
                  1
                  /* TEXT */
                )
              ]),
              taro.createBaseVNode("view", _hoisted_24, [
                _cache[15] || (_cache[15] = taro.createBaseVNode(
                  "text",
                  { class: "result-label" },
                  "难度:",
                  -1
                  /* CACHED */
                )),
                taro.createBaseVNode(
                  "text",
                  _hoisted_25,
                  taro.toDisplayString($setup.difficultyText),
                  1
                  /* TEXT */
                )
              ])
            ]),
            taro.createBaseVNode("view", _hoisted_26, [
              taro.createBaseVNode(
                "view",
                {
                  class: "action-btn",
                  onTap: _cache[3] || (_cache[3] = (...args) => $setup.shareResult && $setup.shareResult(...args))
                },
                _cache[16] || (_cache[16] = [
                  taro.createBaseVNode(
                    "text",
                    { class: "btn-text" },
                    "分享",
                    -1
                    /* CACHED */
                  )
                ]),
                32
                /* NEED_HYDRATION */
              ),
              taro.createBaseVNode(
                "view",
                {
                  class: "action-btn primary",
                  onTap: _cache[4] || (_cache[4] = (...args) => $setup.playAgain && $setup.playAgain(...args))
                },
                _cache[17] || (_cache[17] = [
                  taro.createBaseVNode(
                    "text",
                    { class: "btn-text" },
                    "再来一局",
                    -1
                    /* CACHED */
                  )
                ]),
                32
                /* NEED_HYDRATION */
              )
            ])
          ],
          32
          /* NEED_HYDRATION */
        )
      ],
      32
      /* NEED_HYDRATION */
    )) : taro.createCommentVNode("v-if", true),
    taro.createCommentVNode(" 暂停遮罩 "),
    $setup.gameStatus === "paused" ? (taro.openBlock(), taro.createElementBlock("view", _hoisted_27, [
      taro.createBaseVNode("view", _hoisted_28, [
        _cache[20] || (_cache[20] = taro.createBaseVNode(
          "text",
          { class: "pause-title" },
          "游戏已暂停",
          -1
          /* CACHED */
        )),
        taro.createBaseVNode(
          "view",
          {
            class: "pause-btn",
            onTap: _cache[7] || (_cache[7] = (...args) => $setup.resumeGame && $setup.resumeGame(...args))
          },
          _cache[19] || (_cache[19] = [
            taro.createBaseVNode(
              "text",
              { class: "btn-text" },
              "继续游戏",
              -1
              /* CACHED */
            )
          ]),
          32
          /* NEED_HYDRATION */
        )
      ])
    ])) : taro.createCommentVNode("v-if", true)
  ]);
}
const component = /* @__PURE__ */ common._export_sfc(_sfc_main, [["render", _sfc_render], ["__file", "D:/code/数独/sudoku-game/src/pages/index/index.vue"]]);
var config = {
  "navigationBarTitleText": "首页"
};
Page(taro.createPageConfig(component, "pages/index/index", { root: { cn: [] } }, config || {}));
